package com.financing.wap.web.controller.api;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.activities.impl.ActivitiesYLYXHDImpl;
import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.ActivitieGiftDTO;
import com.financing.wap.dto.ActivitiesWeChatGiftDTO;
import com.financing.wap.dto.FaUserWechatDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IActivitieGiftService;
import com.financing.wap.service.IUserService;
import com.financing.wap.util.Constants;
import com.financing.wap.util.DTOdateSetUtil;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.StringUtil;
import com.financing.wap.util.WeChatGiftXMLUtil;
import com.financing.wap.util.WechatUtil;
import com.financing.wap.vo.ActivitieGiftVo;
import com.financing.wap.web.controller.BaseController;
import com.financing.wap.weixin.dto.SendRedPack;
import com.financing.wap.weixin.resp.SendRedPackResp;
import com.financing.wap.weixin.util.WeixinSign;

@Controller("activitieGiftController")
@RequestMapping("/api/activitieGift")
public class ActivitieGiftController extends BaseController  { 

	private Logger logger = Logger.getLogger(getClass());
	
	private static final  Object b = new Object();
	
	@Autowired
	private IActivitieGiftService activitieGiftServiceImpl;
	
	@Autowired
	private IUserService userService;
	
	@RequestMapping("/list")
	@ResponseBody
	public ResultMap activityRegister(HttpServletRequest request, ActivitieGiftDTO activitieGiftDTO){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query activity gift .......");
			
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			
			activitieGiftDTO.setFaUserId(loginUser.getId());
			Pager pager = null;
			if(request.getParameter("pageNo") != null){
				pager = new Pager();
				pager.setPageNo(Integer.valueOf(request.getParameter("pageNo")));
				pager.setPageSize(Integer.valueOf(request.getParameter("pageSize")));
				pager.setTotalCount(activitieGiftServiceImpl.countActivitiesGift(loginUser.getId()));
				result.setAttribute("pager", pager);
			}
			List<ActivitieGiftVo> list	= activitieGiftServiceImpl.queryActivitieGiftDTOList(activitieGiftDTO,pager);
			for (ActivitieGiftVo bean :list) {
				if(bean == null){
					continue;
				}
				if(Constants.ACTIVITIES_CODE_ZCSHB88.equals(bean.getActiviesCode())){
					checkActiviesEndTime(bean);
				}
				if(Constants.ACTIVITIES_CODE_SDHD.equals(bean.getActiviesCode())){
					bean.setValidTime(bean.getFaAuthValidTime());
					if(bean.getValidTime().before(new Date(System.currentTimeMillis()))){
						bean.setaStatus("03");
					}
				}
				
			}
			result.setAttribute("list", list);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setMessage("红包信息查询成功");
		}catch(Exception e){
			log.error("query activity gift error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	/**
	 * 注册送88元红包-失效时间特殊处理
	 * @param bean
	 */
	private void checkActiviesEndTime(ActivitieGiftVo bean){
		bean.setValidTime(DateUtil.getZCSHB88ActivitiesEndTime(bean.getGetTime(),3,bean.getValidTime()));
	}
	
	
	@RequestMapping("/getGift")
	@ResponseBody
	public ResultMap getGift(HttpServletRequest request){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("create activity gift .......");
			
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			
			
			
			if(null != loginUser){
				ActivitieGiftDTO activitieGiftDTO  = new ActivitieGiftDTO();
				activitieGiftDTO.setFaUserId(loginUser.getId());
				activitieGiftDTO.setActiviesCode("SDHD");
				activitieGiftDTO.setaSource("04");
				activitieGiftDTO.setaType("01");
				activitieGiftDTO.setaStatus("01");
				activitieGiftDTO.setCreateBy(loginUser.getId().toString());
				activitieGiftDTO.setUpdateBy(loginUser.getId().toString());
				
				int actFlag = activitieGiftServiceImpl.isActivitieEnd("SDHD");
				if(actFlag== 1)	{
					// 活动已结束
					result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_END_TIME);
					result.setStatus(ResultMap.STATUS.SUCCESS);
					result.setMessage("活动已结束");
					return result;
				}else if(actFlag == 2){
					// 奖金池已耗光
					result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_EMPTY);
					result.setStatus(ResultMap.STATUS.SUCCESS);
					result.setMessage("红包已抽光");
					return result;
				}
				
				//判断是否已经领到过红包 领到过红包则不再领取
				List<ActivitieGiftDTO> listHB = activitieGiftServiceImpl.queryGifts(activitieGiftDTO);
				if((null==listHB || listHB.size() <=0)){
					List<ActivitieGiftDTO> list = activitieGiftServiceImpl.sendGift(activitieGiftDTO);
					BigDecimal totalAmount = new BigDecimal(0);
					BigDecimal openAmount = new BigDecimal(0);
				   for(ActivitieGiftDTO tmp : list){
					   totalAmount = totalAmount.add(tmp.getaAmount());
					   if("02".equals(tmp.getaStatus())){
							openAmount = tmp.getaAmount();
						}
				   }
				   result.setAttribute("totalAmount", totalAmount.setScale(2,RoundingMode.HALF_EVEN));
				   result.setAttribute("openAmount", openAmount);
				   result.setAttribute("countHongBao", list.size() - 1);
					result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
					result.setStatus(ResultMap.STATUS.SUCCESS);
					result.setMessage("创建红包成功");
					return result;
				}
			}
			
			result.setStatusCode(ResultMap.STATUS_CODE_GIFT_HAS_BROUGHT);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setMessage("创建红包成功");
		}catch(Exception e){
			log.error("create activity gift error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
	@RequestMapping("/queryGift")
	@ResponseBody
	public ResultMap queryGift(HttpServletRequest request){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query activity gift .......");
			
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			
			BigDecimal totalAmount = new BigDecimal(0);
			BigDecimal openAmount = new BigDecimal(0);
			List<ActivitieGiftDTO> listHB = new ArrayList<ActivitieGiftDTO>();
			if(null != loginUser){
				ActivitieGiftDTO activitieGiftDTO  = new ActivitieGiftDTO();
				activitieGiftDTO.setFaUserId(loginUser.getId());
				activitieGiftDTO.setActiviesCode("SDHD");
				listHB = activitieGiftServiceImpl.queryGifts(activitieGiftDTO);
				result.setAttribute("list", listHB);
				// 增加红包总额 已解锁红包金额
				for(ActivitieGiftDTO tmp : listHB){
					totalAmount = totalAmount.add(tmp.getaAmount());
					if("02".equals(tmp.getaStatus())){
						openAmount = openAmount.add(tmp.getaAmount());
					}
				}
			}
			result.setAttribute("totalAmount", totalAmount);
			result.setAttribute("openAmount", openAmount);
			result.setAttribute("countHongBao", listHB.size() - 1);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setMessage("查询红包成功");
		}catch(Exception e){
			log.error("query activity gift error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	@RequestMapping("/queryylyxhdDetail")
	@ResponseBody
	public ResultMap queryylyxhdDetail(HttpServletRequest request){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query activity queryylyxhdDetail begin .......");
			
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			
			//可提现金额
			BigDecimal totalAmount = new BigDecimal(0);
			//好友分享得到金额
			BigDecimal shareAmount = new BigDecimal(0);
			//是否有认证红包
			Boolean authGiftFlag = false;
			//是否有分享红包
			Boolean shareGiftFlag = false;
			//认证红包状态
			String authGiftStatus = null;//01 已开启，02 未开启
			//认证状态
			String authStatus = null;//01 已认证，02 未认证 ，03 认证中  04 认证失败
			//获取红包详细
			ActivitieGiftDTO activitieGiftDTO  = new ActivitieGiftDTO();
			activitieGiftDTO.setActiviesCode(ActivitiesYLYXHDImpl.activitiesCode);
			activitieGiftDTO.setFaUserId(loginUser.getId());
			List<ActivitieGiftDTO> listShareUser = activitieGiftServiceImpl.queryGifts(activitieGiftDTO);
			
			for(ActivitieGiftDTO bena:listShareUser){
				
				//可提现金额-状态是已生效的红包金额
				//aStatus 01:生效中，02：已生效，03：失效，04：提现
				if(Constants.ActivitieGiftDTO.STATUS_EFFECT.equals(bena.getaStatus())){
					totalAmount = totalAmount.add(bena.getaAmount());
				}
				
				//好友助力金额-来源是分享，状态是已生效或者已经提现
				//aSource 01注册。02 分享
				//aStatus 01:生效中，02：已生效，03：失效，04：提现
				if(Constants.ActivitieGiftDTO.SOURCE_SHARE.equals(bena.getaSource())){
					if(Constants.ActivitieGiftDTO.STATUS_EFFECT.equals(bena.getaStatus()) || Constants.ActivitieGiftDTO.STATUS_WITHDRAWALS.equals(bena.getaStatus())){
					shareGiftFlag = true;
					shareAmount = shareAmount.add(bena.getaAmount());
					}
				}
				
				//判断是否有认证红包 - 红包是否开启，认证是否领取
				//aStatus 01:生效中，02：已生效，03：失效，04：提现
				if(Constants.ActivitieGiftDTO.SOURCE_REGISTER.equals(bena.getaSource())){
					authGiftFlag = true;
					if(Constants.ActivitieGiftDTO.STATUS_EFFECT.equals(bena.getaStatus()) || Constants.ActivitieGiftDTO.STATUS_WITHDRAWALS.equals(bena.getaStatus())){
						authGiftStatus= "01";
						authStatus = "01";
					}else{
						authGiftStatus = "02";
						authStatus = "02";
						//查询用户详细信息
						UserDTO faUserDTO = userService.queryUserById(loginUser.getId());
						log.info("#@#@#@:"+faUserDTO.getRole());
						if(Constants.USER_ROLE_AUDIT.equals(faUserDTO.getRole())){
							authStatus = "03";
						}else if(Constants.USER_ROLE_AUDIT_FAILURE.equals(faUserDTO.getRole())){
							authStatus = "04";
						}
					}
				}
			}
					
			result.setAttribute("totalAmount", totalAmount);
			result.setAttribute("shareAmount", shareAmount);
			result.setAttribute("authGiftFlag", authGiftFlag);
			result.setAttribute("shareGiftFlag", shareGiftFlag);
			result.setAttribute("authGiftStatus", authGiftStatus);
			result.setAttribute("authStatus", authStatus);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setMessage("查询queryylyxhdDetail成功");
			logger.info("query activity queryylyxhdDetail end .......");
		}catch(Exception e){
			log.error("query queryylyxhdDetail error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	

	@RequestMapping("/queryylyxhdShareList")
	@ResponseBody
	public ResultMap queryylyxhdShareList(HttpServletRequest request){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query queryylyxhdShareList begin .......");
			
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			
			//好友分享得到金额
			BigDecimal shareAmount = new BigDecimal(0);
			
			//获取红包详细
			ActivitieGiftDTO activitieGiftDTO  = new ActivitieGiftDTO();
			activitieGiftDTO.setActiviesCode(ActivitiesYLYXHDImpl.activitiesCode);
			activitieGiftDTO.setFaUserId(loginUser.getId());
			activitieGiftDTO.setaSource(Constants.ActivitieGiftDTO.SOURCE_SHARE);
			List<Map<String, Object>> listShareUser = activitieGiftServiceImpl.queryYLYXHDGifts(activitieGiftDTO);
			for(Map<String, Object> bena:listShareUser){
				//将手机号加密
				bena.put("U_LOGIN_NAME", StringUtil.encryptCardNumber(bena.get("U_LOGIN_NAME").toString()));
				
				//金额累加
				shareAmount = shareAmount.add((BigDecimal)bena.get("A_AMOUNT"));
			}
			
			
			result.setAttribute("listShareUser", listShareUser);
			result.setAttribute("shareAmount", shareAmount);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setMessage("查询queryylyxhdShareList成功");
			logger.info("query activity queryylyxhdShareList end .......");
		}catch(Exception e){
			log.error("query activity queryylyxhdShareList error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
	/**
	 * 2016元宵活动提现
	 * @param request
	 * @return
	 */
	@RequestMapping("/ylyxhdWithdrawals")
	@ResponseBody
	public ResultMap ylyxhdWithdrawals(HttpServletRequest request){
		ResultMap result = new ResultMap();
		
		//获取活动code
		String activitiesCode = request.getParameter("createsCode");
		
		if(StringUtil.isNullOrEmptyStr(activitiesCode)){
			activitiesCode = ActivitiesYLYXHDImpl.activitiesCode;
		}
		
		//防止同一个多次登录并发。同时提现
		synchronized (b) {
			try{
				logger.info("execute ylyxhdWithdrawals begin .......");				
				Session session = SessionUtil.getSession();
				UserDTO loginUser = session.getUser();
				if(loginUser == null){
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
					result.setMessage("未登录");
					return result;
				}
				//活动判断
				/*int actFlag = activitieGiftServiceImpl.isActivitieEnd(ActivitiesYLYXHDImpl.activitiesCode);
				if(actFlag== 1)	{
					// 活动已结束
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.ACTIVITIES_DATE_IS_OUT);
					result.setAttribute("status", ResultMap.ACTIVITIES_DATE_IS_OUT);
					result.setMessage("活动已结束");
					return result;
				}else if(actFlag == 2){
					// 奖金池已耗光
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.ACTIVITIES_DATE_IS_OUT);
					result.setAttribute("status", ResultMap.ACTIVITIES_DATE_IS_OUT);
					result.setMessage("奖金池已耗光");
					return result;
				}*/
				//可提现金额
				BigDecimal totalAmount = new BigDecimal(0);
				//微信最大金额
				BigDecimal weChatAmount = new BigDecimal(200);
				
				//获取个人可提现红包
				ActivitieGiftDTO activitieGiftDTO  = new ActivitieGiftDTO();
				activitieGiftDTO.setActiviesCode(activitiesCode);
				
				activitieGiftDTO.setFaUserId(loginUser.getId());
				if(activitiesCode.equals("cd500")){
					activitieGiftDTO.setaStatus(Constants.ActivitieGiftDTO.STATUS_IN_EFFECT);
				}else{
					activitieGiftDTO.setaStatus(Constants.ActivitieGiftDTO.STATUS_EFFECT);
				}
				
				List<ActivitieGiftDTO> listShareUser = activitieGiftServiceImpl.queryGifts(activitieGiftDTO);
				
				if(listShareUser == null || listShareUser.size() <=0){
					log.info("execute ylyxhdWithdrawals listShareUser is null!!!");
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
					result.setMessage("违法操作");
					return result;
				}
				
				//获取用户微信信息
				FaUserWechatDTO faUserWechatDTO =  new FaUserWechatDTO();
				faUserWechatDTO.setUserId(loginUser.getId());
				faUserWechatDTO = userService.getFaUserWechatDTO(faUserWechatDTO);
				if(faUserWechatDTO == null || StringUtils.isBlank(faUserWechatDTO.getMpOpenid())){
					log.info("execute ylyxhdWithdrawals MpOpenid is null!!!");
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_WECHAT_ASSOCIATED_USER_ERROR);
					result.setMessage("微信未授权");
					return result;
				}
				
				//获取个人可提现
				for(ActivitieGiftDTO bean:listShareUser){
					totalAmount = totalAmount.add(bean.getaAmount());
				}
				
				
				log.info("execute ylyxhdWithdrawals parameter is SUCCESS!!!");
				//添加-微信红包-状态
				//大于200 分开发红包
				//小于直接发
				ActivitiesWeChatGiftDTO activitiesWeChatGiftDTO = new ActivitiesWeChatGiftDTO();
				DTOdateSetUtil.setCreateInfo(activitiesWeChatGiftDTO);
				DTOdateSetUtil.setUpdateInfo(activitiesWeChatGiftDTO);
				activitiesWeChatGiftDTO.setActiviesCode(activitiesCode);//活动来源
				activitiesWeChatGiftDTO.setFaUserId(loginUser.getId());
				activitiesWeChatGiftDTO.setwOpenid(faUserWechatDTO.getMpOpenid());//查询微信
				activitiesWeChatGiftDTO.setwUnionid(faUserWechatDTO.getUnionid());//查询微信
				activitiesWeChatGiftDTO.setaStatus("01");
				if(totalAmount.compareTo(weChatAmount) > 0){
					log.info("execute ylyxhdWithdrawals totalAmount > 200!!!"+totalAmount);
//					result.setStatus(STATUS.FAILE);
//					result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
//					result.setMessage("违法操作");
//					return result;
					
					
				BigDecimal sendWeChatAmount = new BigDecimal(200);	
					do{
						
							//260 第一次循环、260-200 = 60  >0 ;第二次循环、 60-200 = -140  < 0 ;sendWeChatAmount = 60 ;    
							if(totalAmount.compareTo(weChatAmount) < 0){
								sendWeChatAmount = totalAmount;
							}
							//添加微信红包
							activitiesWeChatGiftDTO.setaAmount(sendWeChatAmount.multiply(new BigDecimal(100)));
							int weChatId =  activitieGiftServiceImpl.addActivitiesWeChatGift(activitiesWeChatGiftDTO);
							
							//发送微信红包
							//红包信息赋值
							SendRedPack sendRedPack =WeChatGiftXMLUtil.getSendRedPack(activitiesCode);
							sendRedPack.setTotal_amount(activitiesWeChatGiftDTO.getaAmount().intValue());
							sendRedPack.setRe_openid(activitiesWeChatGiftDTO.getwOpenid());
							sendRedPack.setSign(WeixinSign.SendRedPackSign(sendRedPack,WeChatGiftXMLUtil.map.get(WeChatGiftXMLUtil.RED_PACK_KEY)));
							SendRedPackResp sendRedPackResp=  WechatUtil.sendRedPack(sendRedPack);
							if(!STATUS.SUCCESS.toString().equals(sendRedPackResp.getReturn_code()) || !STATUS.SUCCESS.toString().equals(sendRedPackResp.getResult_code()) ){
								result.setStatus(STATUS.FAILE);
								result.setStatusCode(sendRedPackResp.getErr_code() == null ? sendRedPackResp.getReturn_code() : sendRedPackResp.getErr_code());
								result.setMessage(sendRedPackResp.getErr_code_des() == null ? sendRedPackResp.getReturn_msg() : sendRedPackResp.getErr_code_des());
								log.error("In check sendGift  error !:"+activitiesWeChatGiftDTO.getwOpenid());
								log.error("In check sendGift  error !:"+result.getStatusCode());
								log.error("In check sendGift  error !:"+result.getMessage());
								log.error("In check sendGift  error !:"+sendRedPackResp.getErr_code_des());
								log.error("In check sendGift  error !:"+sendRedPackResp.getReturn_msg());
								result.setAttribute("totalAmount",0);
								result.setStatusCode(ResultMap.STATUS_CODE_WECHAT_RED_PACK_ERROR);
								result.setStatus(ResultMap.STATUS.ERROR);
								return result;
							}else{
							
								//获取个人可提现-状态改成04(已提现)
								for(ActivitieGiftDTO bean:listShareUser){
									//修改状态
									bean.setaStatus(Constants.ActivitieGiftDTO.STATUS_WITHDRAWALS);
									bean.setUpdateBy(loginUser.getId().toString());
									activitieGiftServiceImpl.updateActivitieGift(bean);
								}
								//修改用户 已经领取
								ActivitiesWeChatGiftDTO updateWeChatGift = new ActivitiesWeChatGiftDTO();
								updateWeChatGift.setId(weChatId);
								updateWeChatGift.setaStatus("02");
								updateWeChatGift.setMchBillno(sendRedPackResp.getMch_billno());
								DTOdateSetUtil.setUpdateInfo(updateWeChatGift);
								activitieGiftServiceImpl.updateActivitiesWeChatGift(updateWeChatGift);
							}
							//循环条件
							totalAmount = totalAmount.subtract(weChatAmount);
							
							//需要继续发送则等待10秒，绕过微信安全监测机制，否则不用等待直接返回
							if(totalAmount.compareTo(new BigDecimal(0)) > 0){
								Thread.sleep(10000);
							}
							
						
					}while(totalAmount.compareTo(new BigDecimal(0)) > 0);
					
				}else{
					
					//添加微信红包
					log.info("execute ylyxhdWithdrawals addActivitiesWeChatGift !!!");
					activitiesWeChatGiftDTO.setaAmount(totalAmount.multiply(new BigDecimal(100)));//小于200直接发-红包金额 
					int weChatId =  activitieGiftServiceImpl.addActivitiesWeChatGift(activitiesWeChatGiftDTO);
					
					//发送微信红包
					//红包信息赋值
					log.info("execute ylyxhdWithdrawals WechatUtil.sendRedPack !!!");
					SendRedPack sendRedPack =WeChatGiftXMLUtil.getSendRedPack(activitiesCode);
					sendRedPack.setTotal_amount(activitiesWeChatGiftDTO.getaAmount().intValue());
					sendRedPack.setRe_openid(activitiesWeChatGiftDTO.getwOpenid());
					sendRedPack.setSign(WeixinSign.SendRedPackSign(sendRedPack,WeChatGiftXMLUtil.map.get(WeChatGiftXMLUtil.RED_PACK_KEY)));
					SendRedPackResp sendRedPackResp=  WechatUtil.sendRedPack(sendRedPack);
					if(!STATUS.SUCCESS.toString().equals(sendRedPackResp.getReturn_code()) || !STATUS.SUCCESS.toString().equals(sendRedPackResp.getResult_code()) ){
						result.setStatus(STATUS.FAILE);
						result.setStatusCode(sendRedPackResp.getErr_code() == null ? sendRedPackResp.getReturn_code() : sendRedPackResp.getErr_code());
						result.setMessage(sendRedPackResp.getErr_code_des() == null ? sendRedPackResp.getReturn_msg() : sendRedPackResp.getErr_code_des());
						log.error("In check sendGift  error !:"+activitiesWeChatGiftDTO.getwOpenid());
						log.error("In check sendGift  error !:"+result.getStatusCode());
						log.error("In check sendGift  error !:"+result.getMessage());
						log.error("In check sendGift  error !:"+sendRedPackResp.getErr_code_des());
						log.error("In check sendGift  error !:"+sendRedPackResp.getReturn_msg());
						result.setAttribute("totalAmount",0);
						result.setStatusCode(ResultMap.STATUS_CODE_WECHAT_RED_PACK_ERROR);
						return result;
					}else{
						//获取个人可提现-状态改成04(已提现)
						for(ActivitieGiftDTO bean:listShareUser){
							//修改状态
							bean.setaStatus(Constants.ActivitieGiftDTO.STATUS_WITHDRAWALS);
							bean.setUpdateBy(loginUser.getId().toString());
							activitieGiftServiceImpl.updateActivitieGift(bean);
						}
						
						//微信红包成功
						//修改用户 已经领取
						log.info("execute ylyxhdWithdrawals updateActivitiesWeChatGift !!!");
						ActivitiesWeChatGiftDTO updateWeChatGift = new ActivitiesWeChatGiftDTO();
						updateWeChatGift.setId(weChatId);
						updateWeChatGift.setaStatus("02");
						updateWeChatGift.setMchBillno(sendRedPackResp.getMch_billno());
						DTOdateSetUtil.setUpdateInfo(updateWeChatGift);
						activitieGiftServiceImpl.updateActivitiesWeChatGift(updateWeChatGift);
					}

				}

				result.setAttribute("totalAmount",totalAmount);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setStatus(ResultMap.STATUS.SUCCESS);
				result.setMessage("execute ylyxhdWithdrawals 成功");
				logger.info("execute ylyxhdWithdrawals end .......");
			}catch(Exception e){
				log.error("execute ylyxhdWithdrawals error!",e);
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			}
		}
		return result;
	}
	
	public static void main(String[] args) {
		
		BigDecimal totalAmount = new BigDecimal(260);
		BigDecimal weChatAmount = new BigDecimal(200);	
		if(totalAmount.compareTo(new BigDecimal(200)) > 0){
			BigDecimal sendWeChatAmount = new BigDecimal(200);	
			do{
				if(totalAmount.subtract(weChatAmount).compareTo(new BigDecimal(0)) < 0){
					sendWeChatAmount = totalAmount;
				}
				System.out.println(sendWeChatAmount);
				totalAmount = totalAmount.subtract(weChatAmount);
				
				
			}while(totalAmount.compareTo(new BigDecimal(0)) > 0);
			
		}
	}
}
